import axios, { type InternalAxiosRequestConfig, type AxiosResponse } from 'axios'

const http = axios.create({
  timeout: 60000
  // baseURL: process.env.VUE_APP_BASE_API
})
// 设置 post、put 默认 Content-Type
http.defaults.headers.post['Content-Type'] = 'application/json'
http.defaults.headers.put['Content-Type'] = 'application/json'
// 添加请求拦截器
http.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = sessionStorage.getItem('token') //TODO
    if (config.headers) {
      config.headers.Authorization = `${token}`
    }
    return config
  },
  (error: unknown) => Promise.reject(error)
)
// 添加响应拦截器
http.interceptors.response.use(
  (response: AxiosResponse) => {
    const { data } = response
    if (data.code == 0) {
      return data
    }
    return Promise.resolve(data)
  },
  (error: { toString: () => string }) => {
    return Promise.reject(error)
  }
)
/**
 * 创建统一封装过的 axios 实例
 * @return {AxiosInstance}
 */
export default http
